package p_400

import java.net.DatagramPacket
import java.net.DatagramSocket
import java.util.logging.Logger

/**
 * udp 服务
 */
abstract class UdpServer(val port: Int, val bufferSize: Int = 8192) : Runnable {

    @Volatile
    var isShutdown = false
    val logger = Logger.getLogger("UdpServer")

    override fun run() {

        val buffer = ByteArray(bufferSize)
        val socket = DatagramSocket(port)
//        socket.soTimeout(10000)
        while (true) {
            if (isShutdown) return
            val incoming = DatagramPacket(buffer, buffer.size)
            try {
                socket.receive(incoming)
                response(socket, incoming)
            } catch (e: Exception) {
                e.printStackTrace()
                isShutdown = true
            }
        }

    }

    fun shutDown() {
        isShutdown = true
    }

    abstract fun response(socket: DatagramSocket, com: DatagramPacket)
}